package com.ieheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ieheima.controller.utils.R;
import com.ieheima.domain.Book;
import com.ieheima.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/books")
public class BoolController {
    @Autowired
    private IBookService iBookService;

    @GetMapping
    public R getAll() {
        return new R(true, iBookService.list());
    }

    //@RequestBody主要用来接收前端传递给后端的json字符串中的数据的请求体中的数据
    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        boolean flag = iBookService.save(book);
        return new R(flag, flag ? "添加成功!" : "添加失败!");
    }

    @PutMapping
    public R update(@RequestBody Book book) {
        return new R(iBookService.updateById(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) {
        return new R(iBookService.removeById(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        return new R(true, iBookService.getById(id));
    }

   /* @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize) {
        IPage<Book> page = iBookService.getPage(currentPage, pageSize);
        //如果当前页码值大于总页码值，那么重新执行查修操作，使用最大页码作为当前页码值
        if (currentPage > page.getPages()) {
            page = iBookService.getPage(1, pageSize);
        }
        return new R(true, page);
    }*/

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book) {
        System.out.println(book);
        IPage<Book> page = iBookService.getPage(currentPage, pageSize, book);
        //如果当前页码值大于总页码值，那么重新执行查修操作，使用最大页码作为当前页码值
        if (currentPage > page.getPages()) {
            page = iBookService.getPage(1, pageSize, book);
        }
        return new R(true, page);
    }

}
